Lesson 7 - Loops

Repeating statements are a major part of programming. Loops will be repeated until a pre-defined condition has been met. Python has two main forms of loops, for and while. Looping is known as iteration.

Iteration - Repeating a group of statements until a pre-defined condition has been met

While loops in python use a condition to control loops. The code within a while loop will only run if the conditional expression is true. Each loop must alter x otherwise the loop will never end. This is known as a infinite loop. At some point the condition must become false!


x = 1
while x<=5:
    print str(x), " squared is " , str(x * x)
    x = x + 1

The output of the above code is -

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25


x = 1
while x<=5:
    print str(x), " squared is " , str(x * x)
  

The output with the x=x+1 removed is below. As x never changes this means that the output is the same and the condition never becomes false. This is an example of a infinite loop.

1 squared is 1
1 squared is 1
1 squared is 1
1 squared is 1
1 squared is 1
1 squared is 1
1 squared is 1
...

infinite loop - A loop which never ends.

Python also has a for loop but handles them very differently from other languages. for loops tend to be used for somthing known as list iteration. However they can be used to iterate over a set of numbers by using a function called range(). The example below will do the exact same as the previous while loop. There is no need to increment x manually (this is done by the for loop). Also the range will end at one less than the second number. So it will end when x is 5 not 6. This may seem odd but it is due to the fact that lists start at 0.


for x in range(1,6):
    print str(x), " squared is " , str(x * x)